package org.gurms.web.filter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RunHSQLListener implements ServletContextListener {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(RunHSQLListener.class);

	public void contextDestroyed(ServletContextEvent event) {
		if(logger.isInfoEnabled()){
			logger.info("HSQL关闭...");
		}

		Connection conn = null;
		try {
			Class.forName("org.hsqldb.jdbcDriver");
			conn = DriverManager.getConnection(
					"jdbc:hsqldb:hsql://localhost/demodb", "sa", "");
			Statement stmt = conn.createStatement();
			stmt.executeUpdate("SHUTDOWN;");
			stmt.close();

			if(logger.isInfoEnabled()){
				logger.info("HSQL关闭");
			}
		} catch (Exception e) {
			logger.error("contextDestroyed(ServletContextEvent)", e); //$NON-NLS-1$
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("contextDestroyed(ServletContextEvent)", e); //$NON-NLS-1$
				}
			}
		}
	}

	public void contextInitialized(ServletContextEvent event) {
		if(logger.isInfoEnabled()){
			logger.info("HSQL开始启动...");
		}
		ServletContext context = event.getServletContext();
		org.hsqldb.Server.main(new String[] { "-database.0",
						context.getRealPath("WEB-INF/hsql/demodb"), "-dbname.0",
						"demodb" });

		if(logger.isInfoEnabled()){
			logger.info("HSQL启动");
		}
	}
}
